package com.capinfo.commons.project.service.security.impl;

import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.capinfo.commons.project.model.security.SystemRole;
import com.capinfo.commons.project.model.security.SystemUser;
import com.capinfo.commons.project.parameter.security.SystemUserParameter;
import com.capinfo.commons.project.service.security.SystemUserService;
import com.capinfo.components.security.cache.manager.SecurityCacheManager;

public class SecurityUserServiceImpl extends SystemUserServiceImpl{
	
	private static final String ROLE_NAMES_SPLIT = ",";
	private static final Log logger = LogFactory.getLog(SystemUserService.class);

	private SecurityCacheManager securityCacheManager;

	public SecurityCacheManager getSecurityCacheManager() {
		return securityCacheManager;
	}

	public void setSecurityCacheManager(SecurityCacheManager securityCacheManager) {
		this.securityCacheManager = securityCacheManager;
	}
	
	public boolean modifyPassword(SystemUserParameter parameter) {
		
		SystemUser user = this.modifyUserPassword(parameter);
		
		if(null != user){
		
			getSecurityCacheManager().modifyUserInCache(user, user.getLogonName());
			return true;
		}
		
		return false;
	}

	public SystemUser saveOrUpdate(SystemUserParameter parameter) {
		
		CacheParameter cacheParameter = super.getCacheParameter(parameter);
		
		// 4. 修改成功后的载入缓存
		SystemUser user = cacheParameter.getUser();
		if( null != user ) {

			getSecurityCacheManager().modifyUserInCache(user, cacheParameter.getUserLogonName());
		}
		
		return user;
	}

	private String getRoleNamesByRoles(Set<SystemRole> systemRoles) {
		StringBuffer roles = new StringBuffer();
		for(SystemRole role: systemRoles){
			roles.append(role.getName() + ROLE_NAMES_SPLIT);
		}
		String roleNames = "";
		if(roles.length() > ROLE_NAMES_SPLIT.length()){
			roleNames = roles.substring(0, roles.length()- ROLE_NAMES_SPLIT.length());
		}
		return roleNames;
	}

	@Override
	public boolean delete(SystemUserParameter parameter) {
		
		SystemUser systemUser = getObjectById(parameter);
		
		boolean token = super.delete(parameter);
		
		// 用户从缓存中删除
		if( ( null != systemUser )&&token ) {

			getSecurityCacheManager().removeUserFromCache(systemUser.getLogonName());
		}
		return token;
	}

	@Override
	public boolean modifyPassword(String logonName, String originalPassword, String newPassword) {
		
		SystemUser user = super.modifyPasswordAndReturnSystemUser(logonName, originalPassword, newPassword);
		
		if(null != user){
			
			getSecurityCacheManager().modifyUserInCache(user, user.getLogonName());
			return true;
		}
		return false;
	}
	
}
